#include "Common.h"
#include "OpenGLShader.h"
#include "Utils/Util.h"
#include "OpenGLShaderProgram.h"

using namespace RayFrame;

void OpenGLShader::internalCreate()
{
  GLuint shaderType = (m_type == VERTEX_SHADER) ? GL_VERTEX_SHADER : GL_FRAGMENT_SHADER ;
  m_ID = glCreateShader(shaderType);
  const char* buffer = m_source.c_str();
  int bufferLen = m_source.length();
  glShaderSourceARB(m_ID, 1,(const GLcharARB**)&buffer, &bufferLen);
  glCompileShaderARB(m_ID);

  GLint compiled;
  glGetObjectParameterivARB(m_ID, GL_COMPILE_STATUS, &compiled);
  if (!compiled)
  {
    GLint blen = 0;  
    GLsizei slen = 0;

    glGetShaderiv(m_ID, GL_INFO_LOG_LENGTH , &blen);       
    if (blen > 1) // display why compiling failed
    {
      GLchar* compiler_log = new GLchar[blen];
      glGetInfoLogARB(m_ID, blen, &slen, compiler_log);
      m_log = "Error while compiling " + m_filename + "\n\n";
      m_log += STRING(compiler_log);
      ErrorMsg( m_log );
      delete [] compiler_log;
    }
    m_isOK = false;
  }
  else
    m_isOK = true;
}

void OpenGLShader::internalDestroy()
{
  glDeleteShader(m_ID);
  m_isOK = false;
}

